
package com.lxyk.yygh.msm.controller;

import com.lxyk.yygh.common.result.Result;
import com.lxyk.yygh.msm.service.MsmService;
import com.lxyk.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis取出
        String code = redisTemplate.opsForValue().get(phone);
        //redis里的验证码不为空
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //code为空，发送短信
        // 如果从redis获取不到，
        // 生成验证码，通过整合短信服务进行发送
        String sixCode = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(phone, sixCode);        // 生成验证码放到redis里面，设置有效时间
        if (isSend){
            redisTemplate.opsForValue().set(phone,sixCode,5, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }

    }


}
